package com.atguigu.gulimall.order.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.OrderConstant;
import com.atguigu.common.em.OrderStatusEnum;
import com.atguigu.common.exception.NoStockException;
import com.atguigu.common.to.mq.SeckillOrderTo;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimall.order.entity.OrderItemEntity;
import com.atguigu.gulimall.order.entity.PaymentInfoEntity;
import com.atguigu.gulimall.order.entity.SpuInfoEntity;
import com.atguigu.gulimall.order.feign.CartClientService;
import com.atguigu.gulimall.order.feign.MemberClientService;
import com.atguigu.gulimall.order.feign.ProductFeignClient;
import com.atguigu.gulimall.order.feign.WareFeignClient;
import com.atguigu.gulimall.order.interceptor.LoginUserInterceptor;
import com.atguigu.gulimall.order.service.OrderItemService;
import com.atguigu.gulimall.order.service.PaymentInfoService;
import com.atguigu.gulimall.order.to.OrderCreatTo;
import com.atguigu.gulimall.order.vo.*;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.order.dao.OrderDao;
import com.atguigu.gulimall.order.entity.OrderEntity;
import com.atguigu.gulimall.order.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {
    @Autowired
    MemberClientService memberClientService;
    @Autowired
    CartClientService cartClientService;
    @Autowired
    WareFeignClient wareFeignClient;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    ProductFeignClient productFeignClient;
    @Autowired
    OrderItemService orderItemService;
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    PaymentInfoService paymentInfoService;
    private ThreadLocal<OrderSubmitVo> threadLocal = new ThreadLocal<>();

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public OrderConfirmVo confirmOrder() {
        OrderConfirmVo confirmVo = new OrderConfirmVo();
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();


        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        //获取登录用户地址信息
        CompletableFuture<Void> memberFuture = CompletableFuture.runAsync(() -> {
            //异步feign调用时是新开一个线程，需要将原来的请求设置到新线程中从而传递请求头中的数据
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<MemberAddressVo> address = memberClientService.getAddress(memberRespVo.getId());
            confirmVo.setAddress(address);

        });

        //获取选中的商品信息
        CompletableFuture<Void> checkItemFuture = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<OrderItemVo> checkItem = cartClientService.getCurrentUserCheckItem();
            confirmVo.setItems(checkItem);
        }).thenRunAsync(() -> {
            List<OrderItemVo> items = confirmVo.getItems();
            if (items != null) {
                List<Long> skuIds = items.stream().map(e -> e.getSkuId()).collect(Collectors.toList());
                R r = wareFeignClient.getSkuHasStock(skuIds);
                List<SkuHasStockVo> hasStockVoList = r.getData(new TypeReference<List<SkuHasStockVo>>() {
                });
                if (!CollUtil.isEmpty(hasStockVoList)) {
                    Map<Long, Boolean> collect = hasStockVoList.stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, SkuHasStockVo::getHasStock));
                    confirmVo.setStocks(collect);
                }
            }

        });
        CompletableFuture.allOf(memberFuture, checkItemFuture).join();

        //设置积分信息
        Integer integration = memberRespVo.getIntegration();
        confirmVo.setIntegration(integration);
        //其他数据自动计算

        //防止重复提交
        String token = UUID.randomUUID().toString().replace("-", "");
        redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId(), token, 30, TimeUnit.MINUTES);
        confirmVo.setOrderToken(token);


        return confirmVo;
    }


    //    @GlobalTransactional，不适用seata的分布式事务，因为不适用于高并发，所以改用MQ
    @Transactional
    @Override
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo vo) {
        threadLocal.set(vo);
        SubmitOrderResponseVo responseVo = new SubmitOrderResponseVo();
        responseVo.setCode(0);
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();

        //下单：创建订单
        String orderToken = vo.getOrderToken();
        // 1. 验证令牌 [必须保证原子性] 返回 0 or 1
        // 0 令牌删除失败 1删除成功
        String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";

        // 原子验证令牌 删除令牌
        Long result = (Long) redisTemplate.execute(new DefaultRedisScript<>(script, Long.class), Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId()), orderToken);
        if (result == 0L) {
            // 令牌验证失败,code设置1
            responseVo.setCode(1);
            return responseVo;
        } else {
            // 令牌验证成功
            //1.创建订单
            OrderCreatTo order = createOrder();
            BigDecimal payAmount = order.getOrder().getPayAmount();
            BigDecimal payPrice = vo.getPayPrice();
            if (Math.abs(payAmount.subtract(payPrice).doubleValue()) < 0.01) {
                //2.验价成功,保存至数据库
                saveOrder(order);
                //3.锁定库存
                WareSkuLockVo wareSkuLockVo = new WareSkuLockVo();
                wareSkuLockVo.setOrderSn(order.getOrder().getOrderSn());
                List<OrderItemEntity> items = order.getItems();
                List<OrderItemVo> locks = items.stream().map(item -> {
                    OrderItemVo orderItemVo = new OrderItemVo();
                    orderItemVo.setSkuId(item.getSkuId());
                    orderItemVo.setCount(item.getSkuQuantity());
                    orderItemVo.setTitle(item.getSkuName());
                    return orderItemVo;
                }).collect(Collectors.toList());
                wareSkuLockVo.setLocks(locks);
                //远程锁库存
                R r = wareFeignClient.orderLockStock(wareSkuLockVo);
                if (r.getCode() == 0) {
                    //锁定库存成功
                    responseVo.setOrder(order.getOrder());

                    //todo ,远程扣减积分
                    // int i=10/0;//订单回滚，库存不会回滚
                    rabbitTemplate.convertAndSend("order-event-exchange", "order-create-order", order.getOrder());
                    return responseVo;
                } else {
                    //锁定库存失败
                    throw new NoStockException((String) r.get("msg"));
                }
            } else {
                responseVo.setCode(2);
                return responseVo;
            }

        }

    }

    @Override
    public OrderEntity getOrderByOrderSn(String orderSn) {
        OrderEntity orderEntity = this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
        return orderEntity;
    }

    private void saveOrder(OrderCreatTo order) {
        OrderEntity orderEntity = order.getOrder();
        this.save(orderEntity);
        List<OrderItemEntity> items = order.getItems();
        orderItemService.saveBatch(items);
    }

    private OrderCreatTo createOrder() {

        OrderCreatTo orderCreatTo = new OrderCreatTo();

        //1.生产订单号
        String orderSn = IdWorker.getTimeId();
        //1.构建订单
        OrderEntity order = buildOrder(orderSn);

        //2.构建订单项
        List<OrderItemEntity> orderItemEntities = buildOrderItems(orderSn);

        //3.计算价格
        computerPrice(order, orderItemEntities);

        orderCreatTo.setOrder(order);
        orderCreatTo.setItems(orderItemEntities);
        orderCreatTo.setFare(order.getFreightAmount());
        orderCreatTo.setPayPrice(order.getPayAmount());

        return orderCreatTo;
    }

    private void computerPrice(OrderEntity order, List<OrderItemEntity> orderItemEntities) {
        BigDecimal totalPrice = new BigDecimal(0);
        BigDecimal gift = new BigDecimal(0);
        BigDecimal growth = new BigDecimal(0);
        for (OrderItemEntity orderItemEntity : orderItemEntities) {
            BigDecimal skuPrice = orderItemEntity.getSkuPrice().multiply(new BigDecimal(orderItemEntity.getSkuQuantity()));
            totalPrice = totalPrice.add(skuPrice);
            gift = gift.add(new BigDecimal(orderItemEntity.getGiftIntegration()));
            growth = growth.add(new BigDecimal(orderItemEntity.getGiftGrowth()));
        }
        //订单总额
        order.setTotalAmount(totalPrice);

        order.setPayAmount(totalPrice.add(order.getFreightAmount()));
        //订单积分等
        order.setGrowth(growth.intValue());
        order.setIntegration(gift.intValue());
    }

    private OrderEntity buildOrder(String orderSn) {
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();

        OrderSubmitVo orderSubmitVo = threadLocal.get();

        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(orderSn);
        //设置会员信息
        orderEntity.setMemberId(memberRespVo.getId());

        R r = wareFeignClient.getFare(orderSubmitVo.getAddrId());
        FareVo fareVo = r.getData(new TypeReference<FareVo>() {
        });

        orderEntity.setFreightAmount(fareVo.getFare());
        //设置收货人信息
        orderEntity.setReceiverCity(fareVo.getMemberAddressVo().getCity());
        orderEntity.setReceiverDetailAddress(fareVo.getMemberAddressVo().getDetailAddress());
        orderEntity.setReceiverName(fareVo.getMemberAddressVo().getName());
        orderEntity.setReceiverPhone(fareVo.getMemberAddressVo().getPhone());
        orderEntity.setReceiverPostCode(fareVo.getMemberAddressVo().getPostCode());
        orderEntity.setReceiverProvince(fareVo.getMemberAddressVo().getProvince());
        orderEntity.setReceiverRegion(fareVo.getMemberAddressVo().getRegion());
        //设置订单状态，0-待付款
        orderEntity.setStatus(0);
        orderEntity.setDeleteStatus(0);
        return orderEntity;
    }

    private List<OrderItemEntity> buildOrderItems(String orderSn) {

        //订单项
        List<OrderItemVo> checkItem = cartClientService.getCurrentUserCheckItem();
        if (!CollUtil.isEmpty(checkItem)) {
            List<OrderItemEntity> collect = checkItem.stream().map(cartItem -> {
                OrderItemEntity orderItemEntity = buildOrderItem(cartItem);
                orderItemEntity.setOrderSn(orderSn);
                return orderItemEntity;
            }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }

    private OrderItemEntity buildOrderItem(OrderItemVo cartItem) {
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        //设置sku
        orderItemEntity.setSkuId(cartItem.getSkuId());
        orderItemEntity.setSkuName(cartItem.getTitle());
        orderItemEntity.setSkuPic(cartItem.getImage());
        orderItemEntity.setSkuPrice(cartItem.getPrice());
        String skuAttrsVals = StringUtils.collectionToDelimitedString(cartItem.getSkuAttr(), ";");
        orderItemEntity.setSkuAttrsVals(skuAttrsVals);
        orderItemEntity.setSkuQuantity(cartItem.getCount());
        //设置spu
        R r = productFeignClient.getSpuInfoBySkuId(cartItem.getSkuId());
        SpuInfoEntity spuInfoEntity = r.getData(new TypeReference<SpuInfoEntity>() {
        });
        orderItemEntity.setSpuId(spuInfoEntity.getId());
        orderItemEntity.setSpuBrand(spuInfoEntity.getBrandId().toString());
        orderItemEntity.setSpuName(spuInfoEntity.getSpuName());
        orderItemEntity.setCategoryId(spuInfoEntity.getCatalogId());
        //设置积分信息
        orderItemEntity.setGiftGrowth(cartItem.getPrice().intValue());
        orderItemEntity.setGiftIntegration(cartItem.getPrice().intValue());
        return orderItemEntity;
    }


    @Override
    public void closeOrder(OrderEntity order) {
        OrderEntity orderEntity = this.getById(order.getId());
        if (orderEntity.getStatus() == OrderStatusEnum.CREATE_NEW.getCode()) {
            OrderEntity update = new OrderEntity();
            update.setId(order.getId());
            update.setStatus(OrderStatusEnum.CANCLED.getCode());
            this.updateById(update);
        }
    }

    @Override
    public PayVo getOrderPayVo(String orderSn) {
        PayVo payVo = new PayVo();

        OrderEntity orderEntity = this.getOrderByOrderSn(orderSn);
        BigDecimal totalAmount = orderEntity.getTotalAmount().setScale(2, BigDecimal.ROUND_UP);
        payVo.setTotal_amount(totalAmount.toString());

        List<OrderItemEntity> list = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));
        OrderItemEntity orderItemEntity = list.get(0);
        payVo.setSubject(orderItemEntity.getSkuName());

        payVo.setBody(orderItemEntity.getSkuAttrsVals());
        payVo.setOut_trade_no(orderSn);
        return payVo;
    }

    @Override
    public PageUtils queryPageWithItem(Map<String, Object> params) {
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();

        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>().eq("member_id", memberRespVo.getId()).orderByDesc("id")
        );

        List<OrderEntity> records = page.getRecords();
        List<OrderEntity> collect = records.stream().map(order -> {
            List<OrderItemEntity> list = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", order.getOrderSn()));
            order.setItemEntities(list);
            return order;
        }).collect(Collectors.toList());
        page.setRecords(collect);
        return new PageUtils(page);
    }

    /**
     * 处理支付宝的异步通知结果
     *
     * @param vo
     * @return
     */
    @Override
    public String handlerPayResult(PayAsyncVo vo) {
        //1.保存交易流水
        PaymentInfoEntity paymentInfoEntity = new PaymentInfoEntity();
        paymentInfoEntity.setAlipayTradeNo(vo.getTrade_no());
        paymentInfoEntity.setOrderSn(vo.getOut_trade_no());
        paymentInfoEntity.setCreateTime(vo.getGmt_create());
        paymentInfoEntity.setPaymentStatus(vo.getTrade_status());
        paymentInfoEntity.setTotalAmount(new BigDecimal(vo.getTotal_amount()));
        paymentInfoService.save(paymentInfoEntity);

        //2.修改订单状态
        String orderSn = vo.getOut_trade_no();
        OrderEntity orderByOrderSn = this.getOrderByOrderSn(orderSn);
        if (vo.getTrade_status().equals("TRADE_SUCCESS") || vo.getTrade_status().equals("TRADE_FINISHED")) {
            orderByOrderSn.setStatus(OrderStatusEnum.PAYED.getCode());
            this.updateById(orderByOrderSn);
        }

        return "success";
    }

    @Override
    public void createSeckillOrder(SeckillOrderTo seckillOrderTo) {
        //todo ,保存订单信息
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(seckillOrderTo.getOrderSn());
        orderEntity.setMemberId(seckillOrderTo.getMemeberId());
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        BigDecimal payAmount = seckillOrderTo.getSeckillPrice().multiply(new BigDecimal(seckillOrderTo.getNum()));
        orderEntity.setPayAmount(payAmount);
        orderEntity.setTotalAmount(payAmount);
        this.save(orderEntity);

        OrderItemEntity orderItemEntity = new OrderItemEntity();
        orderItemEntity.setOrderSn(seckillOrderTo.getOrderSn());
        orderItemEntity.setRealAmount(payAmount);
        orderItemEntity.setSkuQuantity(seckillOrderTo.getNum());
        orderItemService.save(orderItemEntity);
    }


}